<?php
/**
 * @Author: liuhongbin
 * @Email: 514660094@qq.com
 * @Date: 2019-02-12 16:15:10
 * @Description:
 * @LastEditors: liuhongbin
 * @LastEditTime: xxx
 */

namespace addons\gs_developer\model\Addons;

use addons\gs_developer\model\DevBaseModel;
use app\common\model\addon\Addons;
use think\facade\Db;

class AddonsModel extends DevBaseModel
{
    protected $name = self::NAME_PREFIX . 'addons';

    protected $type = array(
        'encrypt_config' => 'json'
    );

    protected $append = array(
        'type_name'
    );

    public function getAddonTables($name)
    {
        $tables = Db::query("SHOW TABLES LIKE '%{$name}_%'");
        foreach ($tables as $key => $value) {
            $tables[$key] = current($value);
        }
        return $tables;
    }

    public function getDropTableSql($name)
    {
        $tables = $this->getAddonTables($name);
        $sql = '';
        foreach ($tables as $key => $value) {
            $value = str_replace(config('database.connections.mysql.prefix'), '__PREFIX__', $value);
            $sql .= "DROP TABLE IF EXISTS `{$value}`;";
        }
        return $sql;
    }


    public function getCreateTableSql($name)
    {
        $tables = $this->getAddonTables($name);

        $prefix = config('database.connections.mysql.prefix');
        $sql = "";
        foreach ($tables as $key => $value) {
            if ($value) {
                $create_table = Db::query("SHOW CREATE TABLE " . $value)[0]['Create Table'];
                // 去除自增id
                $create_table = preg_replace('/AUTO_INCREMENT=\d+ /', '', $create_table);
                // 前缀替换__PREFIX__
                $create_table = str_replace('CREATE TABLE `' . $prefix, 'CREATE TABLE IF NOT EXISTS `__PREFIX__', $create_table);
                $sql .= $create_table . ";

";
            }
        }
        return $sql;
    }

    public function getTypeNameAttr($val, $data)
    {
        $types = (new Addons())->_types;
        return $types[$data['type']];
    }
}
